﻿Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text.RegularExpressions
Imports Microsoft.VisualBasic

Public Class Form1
    Dim nowAddress As String = ""
    Dim ipChecked As Integer = 0

    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        My.Settings("emailTo") = txtEmail.Text
        My.Settings.Save()
        NotifyIcon1.Visible = False
        writeLog("Time: " & Now.ToString & " Shutting Down IP Watcher!")

    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        lblLoalIp.Text = getLocalIP()
        
        writeLog("Time: " & Now.ToString & " Application started! as user: " & My.User.Name)
        lblCheckedTimes.Text = "# of IP Checks: " & ipChecked
        txtEmail.Text = My.Settings("emailTo")
        Timer1.Interval = My.Settings("interval")
        Dim thisIp As String = setIp()
        If thisIp <> "" Then
            lblIPAddress.Text = thisIp
            nowAddress = thisIp
        Else
            writeLog("Time: " & Now.ToString & " Could not recieve IP from web: " & thisIp)
            lblIPAddress.Text = "Can not Read Ip: " & thisIp
            nowAddress = ""
        End If
        If My.Settings("firstRun") = True Then
            My.Settings("firstRun") = False
            settings.setForm(Me)
            settings.Show()
            Dim a As New ServiceReference1.ServiceSoapClient

        End If


    End Sub
    Private Function getLocalIP() As String
        Try
            'Dim adapters As System.Net.NetworkInformation.NetworkInterface() = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
            'Dim adapter As System.Net.NetworkInformation.NetworkInterface
            'Dim ipProp As System.Net.NetworkInformation.IPv4InterfaceStatistics
            'For Each adapter In adapters
            'ipProp = adapter.GetIPv4Statistic
            'ipProp.GetIPv()
            'Next adapter
            Dim LocalHostName As String

            LocalHostName = System.Net.Dns.GetHostName()
            Dim ipEnter As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(LocalHostName)          
            For Each curAdd In ipEnter.AddressList

                ' Display the type of address family supported by the server. If the
                ' server is IPv6-enabled this value is: InternNetworkV6. If the server
                ' is also IPv4-enabled there will be an additional value of InterNetwork.
                ' Console.WriteLine(("AddressFamily: " + curAdd.AddressFamily.ToString()))


                If curAdd.AddressFamily.ToString.Contains("V6") Then
                Else
                    Return curAdd.ToString()
                End If

                ' Display the server IP address in the standard format. In 
                ' IPv4 the format will be dotted-quad notation, in IPv6 it will be
                ' in in colon-hexadecimal notation.
                ' Console.WriteLine(("Address: " + curAdd.ToString()))

                ' Display the server IP address in byte format.
                'Console.Write("AddressBytes: ")
            Next curAdd


            Return ""




        Catch ex As Exception
            Return ""
        End Try
    End Function


    Private Function setIp() As String
        Try
            Dim wc As New System.Net.WebClient
            wc.BaseAddress = "http://checkip.dyndns.org/"
            Dim str As String = wc.DownloadString("http://checkip.dyndns.org/")
            Dim parse1 As String = "<html><head><title>Current IP Check</title></head><body>Current IP Address: "
            Dim parse2 As String = "</body></html>"
            str = str.Replace(parse1, "")
            str = str.Replace(parse2, "")
            str = str.Replace(" ", "")
            str = str.Replace(vbNewLine, "")
            If str <> "" Then
                'lblIPAddress.Text = str
                lblStatusIp.Text = "IP Address: " & str
                Return str
            Else
                lblStatusIp.Text = "IP Address: " & str
                Return ""
            End If
        Catch ex As Exception
            lblStatusIp.Text = ex.Message
            Return ""
        End Try
    End Function

    Private Sub btnTestEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestEmail.Click
        Try
            Dim email As New Net.Mail.SmtpClient(My.Settings("smtpserver").ToString)
            email.UseDefaultCredentials = True
            email.Credentials = New Net.NetworkCredential(My.Settings("loginname").ToString, My.Settings("password").ToString)
            email.EnableSsl = My.Settings("ssl")

            Dim msg As New Net.Mail.MailMessage(My.Settings("emailfrom").ToString, txtEmail.Text)
            msg.Subject = "Ip Test Email"
            msg.Body = "Current Ip Address: " & nowAddress & vbNewLine & "Time: " & Now.ToString
            ' email.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIi
            email.Send(msg)
            writeLog("Time: " & Now.ToString & " Test email Succuessfully sent.")
        Catch ex As Exception
            writeLog("Time: " & Now.ToString & " Error sending test email " & ex.Message)
            MsgBox("Error sending test email: " & ex.Message)
        End Try
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Try
            If chkEnabled.Checked = True Then
                ipChecked += 1
                lblCheckedTimes.Text = "# of IP Checks: " & ipChecked
                Dim newIp As String = setIp()
                writeLog("Time: " & Now.ToString & " IP Check Start")
                If newIp <> "" Then
                    If newIp = nowAddress Then
                        writeLog("Time: " & Now.ToString & " IPs are the same: " & newIp & " = " & nowAddress)
                    Else
                        writeLog("Time: " & Now.ToString & " IPs have changed: " & newIp & " <> " & nowAddress & " Sending Email Warning!")
                        lblIPAddress.Text = newIp
                        sendEmailWarning(nowAddress, newIp)
                        nowAddress = newIp
                    End If
                Else
                    writeLog("Time: " & Now.ToString & " Could not recieve IP from web: " & newIp)
                End If
            End If
        Catch ex As Exception
            writeLog("Time: " & Now.ToString & " Error processing ip changes " & ex.Message)
        End Try
    End Sub
    Private Sub sendEmailWarning(ByVal oldIp As String, ByVal newIP As String)
        Try
            Dim email As New Net.Mail.SmtpClient(My.Settings("smtpserver").ToString)
            email.UseDefaultCredentials = True
            email.Credentials = New Net.NetworkCredential(My.Settings("loginname").ToString, My.Settings("password").ToString)
            email.EnableSsl = My.Settings("ssl")

            Dim msg As New Net.Mail.MailMessage(My.Settings("emailfrom").ToString, txtEmail.Text)
            msg.Subject = "Ip Change"
            msg.Body = "Old Ip Address: " & oldIp & vbNewLine & "New Ip Address: " & newIP & vbNewLine & "Time: " & Now.ToString
            ' email.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIi
            email.Send(msg)
            writeLog("Time: " & Now.ToString & " Warning email Succuessfully sent.")
        Catch ex As Exception
            writeLog("Time: " & Now.ToString & " Error sending warning email " & ex.Message)
        End Try
    End Sub

    Private Sub btnMin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMin.Click
        Me.Hide()
        NotifyIcon1.Text = "Ip Watch : " & nowAddress
    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        Me.Show()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        My.Settings("emailTo") = txtEmail.Text
        My.Settings.Save()
        NotifyIcon1.Visible = False
        writeLog("Time: " & Now.ToString & " Shutting Down IP Watcher!")
        End
    End Sub

    Private Sub MinimizeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MinimizeToolStripMenuItem.Click
        Me.Hide()
        NotifyIcon1.Text = "Ip Watch : " & nowAddress
    End Sub

    Private Sub SettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SettingsToolStripMenuItem.Click
        settings.setForm(Me)
        settings.Show()
    End Sub
    Private Sub writeLog(ByVal text As String)
        Try
            Dim writer As New IO.StreamWriter("log.txt", True)
            writer.WriteLine(text)
            writer.Close()
            writer = Nothing
        Catch ex As Exception
            MsgBox("Error Writing Log File: " & ex.Message)
        End Try
    End Sub

    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click
        viewlog.Show()
        viewlog.doLog()
    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        AboutBox.Show()
    End Sub

    Private Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem3.Click
        netInfo.Show()
        netInfo.getNetInfo()
    End Sub

    Private Sub txtEmail_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtEmail.LostFocus
        My.Settings("emailTo") = txtEmail.Text
        My.Settings.Save()
    End Sub
End Class
